import React, { Component } from 'react'

import { Context, WithStore } from './util'

import Footer from './footer'
import Form from './form'
import List from './list'

import './style.css'


export default class Index extends Component {
    constructor(props) {
        super(props)
        this.state = {
            data: [
                {
                    id: 0,
                    title: '吃饭',
                    checked: true,
                },
                {
                    id: 1,
                    title: '看书',
                    checked: true,
                },
                {
                    id: 2,
                    title: '睡觉',
                    checked: false,
                },
            ],
            change: this.change,
            del: this.del,
            add: this.add,
        }
    }
    change = (item) => {
        item.checked = !item.checked
        let newData = [...this.state.data];
        let index = newData.findIndex(i => i.id === item.id);
        newData[index] = item
        this.setState({
            data: newData
        })
    }
    del = (item) => {
        let newData = [...this.state.data];
        let index = newData.findIndex(i => i.id === item.id);
        newData.splice(index, 1)
        this.setState({
            data: newData
        })
    }
    add = (title) => {
        let newItem = {
            id: this.state.data.length,
            title,  
            checked: false,
        }
        let newData = [...this.state.data, newItem];
        this.setState({
            data: newData
        })
    }

    render() {
        return (
            <Context.Provider value={this.state}>
                <div  className="todoList">
                    <Form />
                    <List />
                    <Footer />
                </div>
            </Context.Provider>
        )
    }
}
